import { Annotation, AnnotationRoot } from "@langchain/langgraph";
import { LLMNode, baseInputVars, SendMessageData, HSKnowledge, BaiLianService, LastMsg, downloadImage } from "../../../core";

export class ImageGenNode extends LLMNode {
    name = "ImageGenNode";
    inputVars = Annotation.Root({
        ...baseInputVars.spec,
        imageCmd: Annotation<string>,
        imageSize: Annotation<string>,
    });

    outputVars = Annotation.Root({
        lastMsg: Annotation<LastMsg>,
    })

    protected OnRunBegin(): void {
        this.OnMessage?.(this, new SendMessageData(this.inputVars.State.convID, this.name, "chat_node_title", { text: "正在生成图片..." }));
    }

    protected OnRunEnd(): void {
        this.OnMessage?.(this, new SendMessageData(this.inputVars.State.convID, this.name, "chat_node_title", { text: "完成图片生成！" }));
    }

    async Run() {
        this.OnRunBegin();
        // const huoshanSvr = new HSKnowledge();
        const bailianSvr = new BaiLianService();
        const result = await bailianSvr.GenOrEidtImage(this.inputVars.State.imageCmd, this.inputVars.State.imageSize as any, "");
        // const result = await huoshanSvr.GenImage(this.inputVars.State.imageCmd, this.inputVars.State.imageSize as any, [])

        console.log(result.content);

        let obj = JSON.parse(result.content as string);

        for (let item of obj) {
            let filename = await downloadImage(item.url);
            item.url = `http://localhost:9000/coeus_coder/api/image/${filename}`;
        }
        this.OnRunEnd();

        this.outputVars.State.lastMsg = {
            content: JSON.stringify(obj), //result.content,
            contentType: "image"
        };
        return this.outputVars.State;
    }
    Stop(): void {
    }

}